package com.laogao.controller;

import com.laogao.model.LogMessage;
import com.laogao.model.LogRequest;
import com.laogao.service.LogWebSocketService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作者微信:it3306
 */
@Controller
public class LogController {

    @MessageMapping("/requestLogs")
    @SendTo("/topic/logs")
    public List<LogMessage> sendFilteredLogs(LogRequest logRequest) {
        // 从 LogWebSocketService 中获取日志缓存
        List<LogMessage> logs = new ArrayList<>(LogWebSocketService.getLogCache());
        // 根据日志级别过滤
        List<LogMessage> filtered = logs.stream().filter(log -> log.getLevel().equalsIgnoreCase(logRequest.getLevel())).collect(Collectors.toList());
        // 返回最新 lineCount 条日志（如果数量多于所需行数，则取最新的）
        int size = filtered.size();
        if (size > logRequest.getLineCount()) {
            return filtered.subList(size - logRequest.getLineCount(), size);
        }
        return filtered;
    }
}
